﻿using ICSharpCode.AvalonEdit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Interactivity;

namespace ModernUILogViewer.Elements.Helpers
{
    public class AppendTextBehavior : Behavior<TextEditor>
    {
        public Action<string> AppendTextAction
        {
            get { return (Action<string>)GetValue(AppendTextActionProperty); }
            set { SetValue(AppendTextActionProperty, value); }
        }

        public bool AutoScrollLastLine
        {
            get { return (bool)GetValue(AutoScrollLastLineProperty); }
            set { SetValue(AutoScrollLastLineProperty, value); }
        }

        // Using a DependencyProperty as the backing store for AppendTextAction.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty AppendTextActionProperty =
            DependencyProperty.Register("AppendTextAction", typeof(Action<string>), typeof(AppendTextBehavior));

        public static readonly DependencyProperty AutoScrollLastLineProperty =
            DependencyProperty.Register("AutoScrollLastLine", typeof(bool), typeof(AppendTextBehavior));

        protected override void OnAttached()
        {
            SetCurrentValue(AppendTextActionProperty, (Action<string>)AssociatedObject.AppendText);
            AssociatedObject.TextChanged += AssociatedObject_TextChanged;
            base.OnAttached();
        }

        void AssociatedObject_TextChanged(object sender, EventArgs e)
        {
            if ((bool)GetValue(AutoScrollLastLineProperty))
            {
                TextEditor editor = (TextEditor)sender;
                editor.ScrollToLine(editor.LineCount);
            }            
        }
    }
}
